<?php
namespace app\common\service;

use think\Model;

class MagazineCategoryService extends BaseService
{

    /**
     * 获取页面分类列表
     * @param $sid
     * @param $name
     * @param $p
     * @param $pageSize
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getList($sid, $name, $p, $pageSize)
    {
        $field = 'cate_id,name,create_time,title';
        $where = [];
        $where['sid'] = $sid;
        $where['status'] = 1;
        if (!empty($name)) {
            $where['name'] = ['like', "%$name%"];
        }
        $list_count = db('magazine_category')->where($where)->count();
        $list = db('magazine_category')
            ->field($field)
            ->where($where)
            ->order('create_time DESC')
            ->limit(($p - 1) * $pageSize, $pageSize)
            ->select();
        if ($list) {
            foreach ($list as $k => &$v) {
                $cate_id = $v['cate_id'];
                $v['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
                $v['count'] = db('magazine')
                    ->where([
                        'sid' => $sid,
                        'status' => ['<>', -1],
                        'category' => ['like', "%$cate_id%"]
                    ])
                    ->count();

                // 兼容老数据  不存在name则将title同步过来
                $v['name'] = $v['name'] ?? $v['title'];
            }
        }
        return ['content' => $list, 'page' => ['count' => $list_count]];
    }


    /**
     * 新增/编辑页面分类
     * @param $sid
     * @param array $postParam
     * @return int|string
     */

    public function saveCategory($sid, $cate_id, $postParam = [])
    {
        $data = [
            'name' => $postParam['name'],
            'title' => $postParam['title'],
            'create_time' => time(),
            'layout_type' => $postParam['layout_type'],
            'ord_list' => $postParam['ord_list'],
            'ord_type' => $postParam['ord_type'],
            'describe' => $postParam['describe'] ?? '',
            'view_pic' => $postParam['view_pic'] ?? '',
            'bg_color' => $postParam['bg_color'] ?? '',
            'content' => $postParam['content'] ? json_encode($postParam['content'], JSON_UNESCAPED_UNICODE) : '',
        ];
        if ($cate_id) {
            $data['update_time'] = time();
            return db('magazine_category')->where('cate_id', $cate_id)->update($data);
        } else {
            $data['sid'] = $sid;
            $data['status'] = 1;
            return db('magazine_category')->insertGetId($data);
        }

    }


    /**
     * 获取详情
     * @param $sid
     * @param $cate_id
     * @return array|false|\PDOStatement|string|Model
     */
    public function getDetail($sid, $cate_id, $field = true)
    {
        $result = db('magazine_category')->field($field)->where(['sid' => $sid, 'cate_id' => $cate_id, 'status' => 1])->find();
        if (!$result) {
            return false;
        }

        // 老数据就不读出来了: 需要用json_decode(htmlspecialchars_decode($result['content']), 1)的数据
        $content = json_decode(htmlspecialchars_decode($result['content']), 1);
        if($content && isset($content['LModules'])){
            unset($result['content']);
        } else {
            $result['content'] = json_decode($result['content'], 1);
        }

        // 兼容老数据  不存在name则将title同步过来
        $result['name'] = (isset($result['name']) && !empty($result['name'])) ? $result['name'] : $result['title'];
        $data['content'] = $result;
        return $data;
    }

    public function getDetailFront($sid, $cate_id)
    {
        $field = 'cate_id,name,title,content,describe,view_pic,layout_type,ord_list,ord_type,bg_color';
        $data = $this->getDetail($sid, $cate_id, $field);
        if(!$data){
            return false;
        }
        $detail = $data['content'];
        if($detail['content']){
            if($detail['ord_list'] == 1){
                $ord = $detail['ord_type'] == 1 ? 'update_time DESC,create_time DESC' : 'update_time ASC,create_time ASC';
            } else {
                $ord = $detail['ord_type'] == 1 ? 'pv DESC' : 'pv ASC';
            }

            foreach ($detail['content'] as $k => &$v){
                // 页面列表
                if($v['type'] == 13){
                    $v['magazine_list'] = db('magazine')
                        ->field('mid,title,describe,view_pic')
                        ->where([
                            'sid' => $sid,
                            'category' => ['like', "%$cate_id%"],
                            'status' => 1
                        ])
                        ->order($ord)
                        ->select();
                }
            }
        }
        return $detail;
    }

    /**
     * 删除页面分类
     * @param $sid
     * @param $cate_id
     * @param $batch
     * @return int
     */
    public function deleteCategory($sid, $cate_id, $batch = 0)
    {
        //查询是否有页面内容使用此分类
        $where = [
            'sid' => $sid,
            'category' => $batch == 0 ? $cate_id : ['in', $cate_id],
            'status' => ['<>', -1]
        ];
        $info = db('magazine')->where($where)->find();
        if ($info) {
            return ['status' => 0, 'msg' => '此分类正在使用，无法删除'];
        }

        $condition = [
            'sid' => $sid,
            'cate_id' => $batch == 0 ? $cate_id : ['in', $cate_id],
        ];
        $result = db('magazine_category')->where($condition)->setField('status', 0);
        return $result === false ? ['status' => 0, 'msg' => '删除失败'] : ['status' => 1, 'msg' => '删除成功'];
    }


}